import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/pinia/modules/user';
import router from '@/router/index';

const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_PATH,
  // 请求头信息
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json;charset=UTF-8'
  },
  // 设置超时时间
  timeout: 100000,
  // 跨域请求时是否需要使用凭证
  withCredentials: true,
  crossDomain: true,
  // 返回数据类型
  responseType: 'json',
  responseEncoding: 'utf8'
});

// http request 拦截器
request.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    config.headers = {
      'x-token': userStore.getToken(),
      'x-user-id': userStore.getUser()?.id,
      ...config.headers
    };
    return config;
  },
  error => {
    ElMessage({
      showClose: true,
      message: error,
      type: 'error'
    });
    return error;
  }
);

// http response 拦截器
request.interceptors.response.use(
  response => {
    if (response.headers['content-type'] === "application/octet-stream") {
      return response;
    } else if (response.data) {
      if (response.data.code && response.data.code === "0") {
        ElMessage.error(response.data.message || '');
        throw response.data;
      }
      return response.data;
    } else {
      ElMessage.error(response.data.message || '');
      if (response.data.data && response.data.data.reload) {
        const userStore = useUserStore();
        userStore.clearStorage();
        router.push({ name: 'login', replace: true }).then(() => {});
      }
      return response.data.message ? response.data : response;
    }
  },
  error => {
    if (!error.response) {
      ElMessage.error('请求出错，请稍候再试。');
      return;
    }

    switch (error.response.status) {
      case 401:
        try {
          const userStore = useUserStore();
          if (userStore.getUser().id) {
            ElMessage.error('登录超时，请重新登录！');
          }
          userStore.clearStorage();
        } catch (e) {
          console.log(e)
        }

        router.push({name: 'login', replace: true}).catch(e => console.log(e));
        break;
      case 403:
        ElMessage.error('权限不足，请与管理员联系！');
        break;
      case 404:
        ElMessage.error('请求资源不存在！');
        break
      case 500:
        ElMessage.error('未知错误！');
        break
      default:
        ElMessage.error('未知错误！');
        break;
    }

    throw error
  }
);

export default request
